package com.yanx.system.web.query;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;
import com.yanx.common.command.Executor;
import com.yanx.common.core.command.PageQryCommand;
import com.yanx.system.base.domain.entity.QSysDept;
import com.yanx.system.base.domain.entity.rel.QSysRoleDept;
import com.yanx.system.base.model.vo.SysRoleVo;
import com.yanx.system.base.query.SysRoleByIdQry;
import lombok.AllArgsConstructor;

import java.util.List;

/**
 * 部门分页查询
 *
 * @author: gotanks
 * @create: 2023-4-12
 */
@AllArgsConstructor
public class DeptListByRoleIdQry extends PageQryCommand<List<Long>> {

    private Long roleId;

    @Override
    public List<Long> execute(Executor executor) {
        SysRoleVo sysRoleVo = executor.execute(new SysRoleByIdQry(roleId));

        QSysDept sysDept = QSysDept.sysDept;
        QSysRoleDept sysRoleDept = QSysRoleDept.sysRoleDept;

        //查询条件
        BooleanBuilder condition = new BooleanBuilder();
        condition.and(sysDept.deleted.eq(false));
        condition.and(sysRoleDept.roleId.eq(roleId));
        if (sysRoleVo.isDeptCheckStrictly()) {
            condition.and(sysDept.id.notIn(
                    queryFactory.select(sysDept.parentId)
                            .from(sysDept)
                            .leftJoin(sysRoleDept).on(sysRoleDept.deptId.eq(sysDept.id))
                            .where(sysRoleDept.roleId.eq(roleId))
            ));
        }

        JPAQuery<Long> query = queryFactory.select(sysDept.id)
                .from(sysDept)
                .leftJoin(sysRoleDept).on(sysRoleDept.deptId.eq(sysDept.id))
                .where(condition)
                .orderBy(sysDept.parentId.asc(), sysDept.orderNum.asc());

        return this.pageList(query);
    }

}